package feces.servlet;

import java.io.IOException;

import javax.persistence.EntityTransaction;
import javax.persistence.RollbackException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import feces.model.StorehouseProduct;
import feces.utility.Utility;

/**
 * 库房商品管理伺服器
 */
@WebServlet(name="storehouse_product", urlPatterns={"/api/storehouse_product"})
@NoArgsConstructor
public class StorehouseProductServlet extends RESTfulServlet {

	private static final long serialVersionUID = -5212253820030127798L;
	
	/**
	 * 字典
	 * 
	 * @author Bromine0x23
	 */
	@NoArgsConstructor(access = AccessLevel.PROTECTED)
	public static class Dictionary extends RESTfulServlet.Dictionary {

		public static final String STOREHOUSE_ID = "storehouse_id";
		
		public static final String PRODUCT_ID = "product_id";
		
		public static final String PK_STOREHOUSE_ID = "pk[storehouse_id]";
		
		public static final String PK_PRODUCT_ID = "pk[product_id]";
		
		public static final String CRITICAL = "critical";
		
		public static final String LIMIT = "limit";
	}

	/**
	 * 响应PUT方法，获取库房商品
	 */
	@Override
	protected Response<StorehouseProduct> responseUpdate(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		Integer storehouse_id = Utility.toInteger(request.getParameter(Dictionary.PK_STOREHOUSE_ID));
		Integer product_id = Utility.toInteger(request.getParameter(Dictionary.PK_PRODUCT_ID));
		if (storehouse_id == null || product_id == null) {
			return invalid("主键不能为空", null);
		}
		final StorehouseProduct storehouse_product = find(
			StorehouseProduct.class,
			new StorehouseProduct.PrimaryKey(storehouse_id, product_id)
		);
		String column = request.getParameter(Dictionary.COLUMN);
		String value = request.getParameter(Dictionary.VALUE);
		if (storehouse_product == null) {
			return invalid("无效的主键", null);
		}
		if (Utility.isEmpty(column)) {
			return invalid("修改域不能为空", null);
		}
		EntityTransaction transaction = getTransaction();
		try {
			transaction.begin();
			switch (column) {
				case Dictionary.CRITICAL: {
					storehouse_product.setCritical(Utility.toInteger(value));
					break;
				}
				case Dictionary.LIMIT: {
					storehouse_product.setLimit(Utility.toInteger(value));
					break;
				}
				default:
					return invalid("无效的修改域", null);
			}
			if (storehouse_product.isValid()) {
				transaction.commit();
				return succeed("修改成功", storehouse_product);
			}
		} catch (IllegalStateException | RollbackException exception){
			exception.printStackTrace();
			return exception("执行发生异常", null);
		} finally {
			if (transaction.isActive()) {
				transaction.rollback();
			}
		}
		return failed("修改失败", null);
	}
	
}
